<template>
  <div id="app" >
    <button @click="changeTheme('coy')">coy主题</button>
    <button @click="changeTheme('tomorrow')">tomorrow主题</button>
    <div class="markdown-box">
      <div class="mark-code"  contenteditable="true" @input="setContent"></div>
      <div :class="`theme-${theme} mark-content`">
        <div id="md-container"></div>
      </div>
    </div>
  </div>
</template>

<script>
import Prism from "prismjs";
import axios from "axios";
export default {
  name: "App",
  data() {
    return {
      theme: "coy",
      value:"123"
    };
  },
  mounted() {
    // this.init();
  },
  methods: {
    init(text) {
      axios.post("http://localhost:3003/mdtohtml",{text:text},).then((res) => {
        let {html,forntMatter} = res.data;
        let app = document.getElementById("md-container");
        //在说有pre前加上复制按钮
        html = html.replace(/<pre>/g, '<div id="copy" class="copy-box"><span class="copy">复制<span></div><pre>');
        app.innerHTML = html;
        console.log(html);
        this.theme = forntMatter.theme
        Prism.highlightAll();
        //绑定复制按钮click
        this.bindCopy()
      });
    },
    bindCopy(){
      let copys = document.querySelectorAll('.copy')
      //遍历所有code添加事件
      copys.forEach(item=>{
        item.addEventListener('click',function(){
          const codeBlock =item.parentElement.nextElementSibling.children[0]
          const codeContent = codeBlock.innerText;
          navigator.clipboard.writeText(codeContent)
            .then(() => {
              console.log('复制成功',codeContent)
            })
            .catch((error) => {
              console.error('复制失败：', error);
            });
        })
      })
    },
    setContent(e){
      console.log(e.target.innerText)
      let text = e.target.innerText
      this.init(text)
    },
    changeTheme(theme) {
      this.theme = theme;
    },
  },
};
</script>

<style lang="scss">
@import url("./style/themes/prism-coy.css");
@import url("./style/themes/prism-tomorrow.css");
html {
  box-sizing: border-box;
}
 
*, *:before, *:after {
  box-sizing: inherit;
}
.markdown-box{
  display: flex;
  height: calc(100vh - 30px);
}
@mixin mark-block {
  width: 50%;
  height: 100%;
  border: solid 1px #606266;
  padding: 10px
}
.mark-code{
  @include mark-block;
  background: #eee;
  &:focus{
    outline: none;
  }
  line-height: 26px;
}
.mark-content{
  @include mark-block;
  border-left: 0;
}
</style>